// api 地址定义
import axios from './axios'
// redux store
import redux from '~/redux/store'
import storage from '~/storage'

// const HOST = 'http://localhost:9080'
const HOST = 'http://192.168.10.12:9080'
// const HOST = 'http://122.114.0.204:9080'

// 热门内容
export const rxPostHot = ({page=1}) => {
  return new Promise((resolve) => {
    // const p = encodeURIComponent("p="+p)

    const p = "p=" + encodeURIComponent(page)

    axios.get(HOST + '/post/hot?' + p).then((response) => {
      resolve(response)
    })
  })
}

// 初始化校验接口, 主要检查登陆令牌有效性
export const rxEcho = (params) => {
  return new Promise((resolve) => {
    storage.getToken((token) => {
      redux.dispatch({type: 'SET_TOKEN', token: token})
      // request
      axios.get(HOST + '/echo', params).then((response) => {
        resolve(response)
      })
    })
  })
}

// 登陆接口
export const rxLogin = (params) => {
  return new Promise((resolve) => {
    axios.post(HOST + '/login', params).then((response) => {
      token = response.token || null

      if (token != null) {
        storage.setToken(token)
        redux.dispatch({type: 'SET_TOKEN', token: token})
      }

      resolve(response)
    })
  })
}

// 退出登陆
export const rxLogout = () => {
  return new Promise((resolve) => {
    axios.get(HOST + '/logout').then((response) => {
      storage.remoteToken()
      redux.dispatch({type: 'SET_TOKEN', token: null})

      resolve(response)
    })
  })
}

// 文章详情
// export const rxPostShow = (id) => {
//   return axios.get(HOST + '/post' + id + '/show', params).then((response) => {
//     resolve(response)
//   })
// }
